package com.rzico.sbl.ui.member

import android.widget.TextView
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityMemberAdressBinding
import com.rzico.sbl.model.AddressData
import com.rzico.sbl.ui.manual.ManualEditActivity
import com.rzico.sbl.viewmodel.AddressViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.helper.bottomHide
import com.xinnuo.common.helper.bottomShow
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.*
import com.xinnuo.slimadapter.SlimAdapter

class MemberAdressActivity : BaseActivity(R.layout.activity_member_adress) {

    private val mBinding by lazy { ActivityMemberAdressBinding.bind(getRootView()) }

    override fun getViewModel() = get<AddressViewModel>()

    private lateinit var mCardId: String
    private lateinit var mMemberId: String
    private lateinit var mMemberPhone: String

    override fun initData() {
        initTitle(title = "收货地址")

        initLayout()

        mBinding.listLayout
            .swipeRefresh
            .isRefreshing = true

        getData()
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关地址信息！"
                }

                recycleList.also { view ->
                    view.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData() }
                    )

                    view.addItemDecoration(SpaceTBDecoration(bottom = 60f))
                    view.addOnScrollChanged(
                        onShow = { mBinding.adressBottom.bottomShow() },
                        onHide = { mBinding.adressBottom.bottomHide(52f) }
                    )

                    mAdapter = SlimAdapter.creator()
                        .register<AddressData>(R.layout.item_adress_list) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_adress_name, bean.consignee)
                                text(R.id.item_adress_phone, bean.phone)
                                text(R.id.item_adress_addr, bean.address)

                                with<TextView>(R.id.item_adress_def) {
                                    it.setCompoundDrawable(
                                        leftDrawable = if (bean.default) R.mipmap.login_yes else R.mipmap.login_no,
                                        leftSize = 15f
                                    )
                                }

                                clicked(R.id.item_adress_def) {
                                    bean.default
                                        .conditionFalse {
                                            defaultAdress(bean.id, index)
                                        }
                                }

                                clicked(R.id.item_adress_edit) {
                                    startActivityEx<MemberAdressEditActivity>(
                                        "memberPhone" to bean.phone,
                                        "bean" to bean
                                    )
                                }

                                clicked(R.id.item_adress_qrcode) {
                                    startActivityEx<MemberAdressCodeActivity>(
                                        "receiverId" to bean.id,
                                        "memberId" to mMemberId
                                    )
                                }

                                clicked(R.id.item_adress_del) {
                                    deleteAdress(bean.id, index)
                                }

                                clicked(R.id.item_adress_manual) {
                                    startActivityEx<ManualEditActivity>(
                                        "receiverId" to bean.id,
                                        "cardId" to mCardId,
                                        "memberId" to mMemberId,
                                        "consignee" to bean.consignee,
                                        "phone" to bean.phone,
                                        "address" to bean.address
                                    )
                                }
                            }
                        }
                        .attachTo(view)
                }
            }
    }

    override fun initListener() {
        mCardId = intent.getExtra("cardId")
        mMemberId = intent.getExtra("memberId")
        mMemberPhone = intent.getExtra("memberPhone")

        mBinding
            .btAdd
            .oneClick {
                startActivityEx<MemberAdressEditActivity>(
                    "memberId" to mMemberId,
                    "memberPhone" to mMemberPhone
                )
            }

        observe<String>("addressList") { updateList() }
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .adressList(mMemberId)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mList.apply {
                        clear()
                        addItems(it)
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

    /**
     * 设为默认地址
     */
    private fun defaultAdress(adressId: String, index: Int) {
        getViewModel()
            .adressDef(adressId)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    showToast("设置成功！")

                    if (mList.any { (it as AddressData).default }) {
                        (mList.first {
                            it as AddressData
                            it.default
                        } as AddressData).default = false
                    }

                    val item = mList.removeAt(index) as AddressData
                    item.default = true
                    mList.add(0, item)

                    mAdapter.notifyDataSetChanged()
                }
            )
    }

    /**
     * 删除地址
     */
    private fun deleteAdress(adressId: String, index: Int) {
        showHintDialog(
            title = "删除地址",
            hint = "确定要删除地址吗？",
            onSure = {
                getViewModel()
                    .adressDel(adressId)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("地址删除成功！")

                            mList.removeAt(index)
                            mAdapter.apply {
                                notifyItemRemoved(index)
                                notifyItemRangeChanged(index, mList.size - index)
                            }

                            mBinding
                                .listLayout
                                .emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                    )
            }
        )
    }

}